﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Diagnostics;
using ThreeByte.ActiveDeck.Config;
using System.Reflection;

namespace ThreeByte.ActiveDeck.Data.UserResponse {
    public class GroupedUserResponseData {
        protected static readonly XNamespace ns = Service.ServiceConfiguration.NAMESPACE;

        public string Presentation {
            get;
            private set;
        }

        public int Section {
            get;
            protected set;
        }

        public Dictionary<int, AggregateUserData> GroupedUserDataElements {
            get;
            set;
        }

        public GroupedUserResponseData(string presentation, int section) {
            Presentation = presentation;
            Section = section;
            GroupedUserDataElements = new Dictionary<int, AggregateUserData>();
        }

        public XElement ToXml() {

            XElement node = new XElement(ns + "UserData", new XAttribute("Presentation", Presentation),
                                                            new XAttribute("Section", Section));

            foreach(int k in GroupedUserDataElements.Keys.OrderBy(p => p)) {
                XElement groupNode = new XElement(ns + "Group", new XAttribute("ID", k));
                groupNode.Add(GroupedUserDataElements[k].ToXml());
                node.Add(groupNode);
            }

            return node;
        }

        public static GroupedUserResponseData ParseXml(XElement node) {

            GroupedUserResponseData userResponseData = new GroupedUserResponseData(node.Attribute("Presentation").Value, int.Parse(node.Attribute("Section").Value));

            foreach(XElement g in node.Elements(ns + "Group")) {                
                    userResponseData.GroupedUserDataElements.Add(int.Parse(g.Attribute("ID").Value), AggregateUserData.ParseXml(g.Element(ns + "Aggregate")));                
            }

            return userResponseData;
        }

    }
}
